<template>
    <div>
        <el-button type="primary" @click="dialogVisible = true">点击打开 Dialog</el-button>
        <div id="container">
        </div>

        <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <span>这是一段信息</span>
            <el-form :model="form">
                <el-form-item label="活动名称">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="活动区域">
                    <el-select v-model="form.region" placeholder="请选择活动区域">

                        <el-option v-for="item in options" :key="item.value" :label="item.label" :disabled="item.disabled"
                            :value="item.value"></el-option>

                    </el-select>
                </el-form-item>
            </el-form>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirm">确 定</el-button>
        </el-dialog>

    </div>
</template>
   
<script>
// 引入antv-G6
import G6 from '@antv/g6'
// 树图的数据
import { treedata } from './treedata'
// G6的配置项



G6.Util.traverseTree((d) => {

    d.leftIcon = {
        style: {
            fill: '#e6fffb',
            stroke: '#e6fffb',
        },
        img: 'https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ',
    };
    return true;
});

G6.registerNode(
    'icon-node',
    {
        options: {
            size: [60, 20], // 宽高
            stroke: '#91d5ff', // 变颜色
            fill: '#fff'// 填充色
        },
        // draw是绘制后的附加操作-节点的配置项  图形分组，节点中图形对象的容器
        draw(cfg, group) {

            // 获取节点的配置
            const styles = this.getShapeStyle(cfg)
            // 解构赋值
            const { labelCfg = {} } = cfg

            const w = styles.width
            const h = styles.height
            // 向分组中添加新的图形 图形 配置 rect矩形 xy 代表左上角坐标 w h是宽高
            const keyShape = group.addShape('rect', {
                attrs: {
                    ...styles,
                    x: -w / 2,
                    y: -h / 2
                }
            })


            if (cfg.leftIcon) {
                const { style, img } = cfg.leftIcon;
                group.addShape('rect', {
                    attrs: {
                        x: 1 - w / 2,
                        y: 1 - h / 2,
                        width: 38,
                        height: styles.height - 2,
                        fill: '#8c8c8c',
                        ...style,
                    },
                });
                //小房子icon
                group.addShape('image', {
                    attrs: {
                        x: 8 - w / 2,
                        y: 8 - h / 2,
                        width: 24,
                        height: 24,
                        img:
                            img ||
                            'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png',
                    },
                    // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
                    name: 'image-shape',
                });
            }
            //左侧绿色圆圈
            // 如果不需要动态增加或删除元素，则不需要 add 这两个 marker


            group.addShape('rect', {
                attrs: {
                    x: 20,
                    y: -20,
                    width: 20,
                    height: 20,
                    fill: 'green',
                },
                name: 'add-item',
                zIndex: 10,
            });


            group.addShape('rect', {
                attrs: {
                    x: 20,
                    y: 0,
                    width: 20,
                    height: 20,
                    fill: 'red',
                },
                name: 'remove-item',
                zIndex: 10,
            });



            //   group.addShape('marker', {
            //     attrs: {
            //       x: 0,
            //       y: 10,
            //       r: 6,
            //       stroke: '#73d13d',
            //       cursor: 'pointer',
            //       // symbol: EXPAND_ICON,
            //     },
            //     // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
            //     name: 'add-item',
            //     zIndex: 10,
            //   });



            //   group.addShape('marker', {
            //     attrs: {
            //       x: 80 - w / 2,
            //       y: 52 - h / 2,
            //       r: 6,
            //       stroke: '#ff4d4f',
            //       cursor: 'pointer',
            //       // symbol: COLLAPSE_ICON,
            //     },
            //     // must be assigned in G6 3.3 and later versions. it can be any string you want, but should be unique in a custom item type
            //     name: 'remove-item',
            //   });


            // 文本文字的配置
            if (cfg.label) {
                group.addShape('text', {
                    attrs: {
                        ...labelCfg.style,
                        text: cfg.label,
                        x: 50 - w / 2,
                        y: 25 - h / 2
                    }
                })
            }

            return keyShape
        },
        // 更新节点后的操作，一般同 afterDraw 配合使用
        update: undefined
    },
    'rect'
)
G6.registerEdge('flow-line', {
    // 绘制后的附加操作
    draw(cfg, group) {
        // 边两端与起始节点和结束节点的交点；
        const startPoint = cfg.startPoint
        const endPoint = cfg.endPoint
        // 边的配置
        const { style } = cfg
        const shape = group.addShape('path', {
            attrs: {
                stroke: style.stroke, // 边框的样式
                endArrow: style.endArrow, // 结束箭头
                // 路径
                path: [
                    ['M', startPoint.x, startPoint.y],
                    ['L', startPoint.x, (startPoint.y + endPoint.y) / 2],
                    ['L', endPoint.x, (startPoint.y + endPoint.y) / 2],
                    ['L', endPoint.x, endPoint.y]
                ]
            }
        })

        return shape
    }
})


// 默认的鼠标悬停会加粗,边框颜色改变
const defaultStateStyles = {
    hover: {
        stroke: '#1890ff',
        lineWidth: 2,
    },
};
// 默认节点的颜色 边 圆角的配置
const defaultNodeStyle = {
    fill: '#91d5ff',
    stroke: '#40a9ff',
    radius: 5,
};
// 默认边的颜色 末尾箭头
const defaultEdgeStyle = {
    stroke: '#91d5ff',
    endArrow: {
        path: 'M 0,0 L 12, 6 L 9,0 L 12, -6 Z',
        fill: '#91d5ff',
        d: -20,
    },
};
// 默认布局
// compactBox 紧凑树布局
// 从根节点开始，同一深度的节点在同一层，并且布局时会将节点大小考虑进去。
const defaultLayout = {
    type: 'compactBox',
    direction: 'TB',
    getId: function getId(d) {
        return d.id;
    },
    getHeight: function getHeight() {
        return 16;
    },
    getWidth: function getWidth() {
        return 16;
    },
    getVGap: function getVGap() {
        return 40;
    },
    getHGap: function getHGap() {
        return 70;
    },
};
// 文本配置项
const defaultLabelCfg = {
    style: {
        fill: '#000',
        fontSize: 12,
    },
};





export default {
    name: 'Home',
    data() {
        return {
            targetModelName:'',
            addId:"",
            targetId: '',
            targetModel: '',
            targetName: '',
            targetType: '',
            evt: '',
            graph: null,
            dialogVisible: false,
            form: {
                name: '',
                region: ''
            },
            options: [{
                label: '一级单位',
                value: '1'
            }, {
                label: '二级单位',
                value: '2'
            }, {
                label: '三级单位',
                value: '3'
            }, {
                label: '四级单位',
                value: '4'
            }, {
                label: '五级单位',
                value: '5'
            }
            ]

        }
    },
    methods: {
        findChildren(data) {
         
        },
        confirm() {
            console.log(this.form);
            this.dialogVisible = false
            console.log(this.dialogVisible);


            this.targetType = this.evt.target.get('type');
            this.targetName = this.evt.target.get('name');
            console.log(this.targetName);
            // 增加元素
            if (this.targetType === 'rect') {
                this.targetModel = this.evt.item.getModel();



                if (this.targetName === 'add-item') {
                    if (!this.targetModel.children) {
                        this.targetModel.children = [];
                    }

                    let targetModelName = this.targetModel.id.split('-')
                    // if(targetModelName[0] == 'root') {


                    // }

                    let wx = {
                        ...this.targetModel,
                    }
                    this.findChildren(wx)
                
                   
                   

                    console.log(wx,'wxxxxx');

                    console.log(this.targetModel,'');
 
                    if (treedata.id == this.targetModel.id) {
                        console.log(31);
                        for (let index = 0; index < treedata.children.length; index++) {
                            this.addId = Number(treedata.children[index].id) + 1;

                        }
                        // this.addId = '1-1-1-1-1'
                    } else {
                          let w=this.targetModel.id.split('-')
                          if(this.targetModel.children.length>0) {
                            w.push(this.targetModel.children.length+1)
                          }else {
                            w.push(1)
                          }
                          this.addId=w.join('-')
                        
                    }




                    // this.targetId = this.form.region;
                    this.targetModel.children.push({
                        id:  this.addId ,
                        label: this.form.name,
                        // leftIcon: {
                        //   style: {
                        //     fill: '#e6fffb',
                        //     stroke: '#e6fffb',
                        //   },
                        //   img:
                        //     'https://gw.alipayobjects.com/mdn/rms_f8c6a0/afts/img/A*Q_FQT6nwEC8AAAAAAAAAAABkARQnAQ',
                        // },
                    });
                    console.log(treedata, '这里是?');
                    this.graph.updateChild(this.targetModel, this.targetModel.id);
                }

            }
        },
        handleClose() {

        },
        G6init() {
            if (typeof window !== 'undefined') {
                window.onresize = () => {
                    if (!this.graph || this.graph.get('destroyed')) return
                    if (!container || !container.scrollWidth || !container.scrollHeight) return
                    this.graph.changeSize(container.scrollWidth, container.scrollHeight)
                }
            }
            // 获取容器
            const container = document.getElementById('container')
            // 获取容器的宽高
            const width = container.scrollWidth
            const height = container.scrollHeight || 500

            const menu = new G6.Menu({
                offsetX: 10,
                offsetY: 10,
                itemTypes: ['node'],
                getContent(e) {

                    const outDiv = document.createElement('div')
                    outDiv.style.width = '100px'
                    outDiv.innerHTML = `<ul>
             <li>增加节点</li>
             <li>删除节点</li>
             <li>查看节点</li>
             <li>编辑节点</li>
             </ul>`
                    return outDiv
                }
            })

            // Graph 是 G6 图表的载体-实例化
            this.graph = new G6.TreeGraph({
                container: 'container', // 图的 DOM 容器
                width,
                height,
                linkCenter: true, // 指定边是否连入节点的中心
                plugins: [menu], // 插件  minimap
                modes: { // 交互模式
                    // default 模式中包含点击选中节点行为和拖拽画布行为;
                    default: [
                        {
                            // 这个是可以展开可以收起
                            // type: 'collapse-expand',
                            onChange: function onChange(item, collapsed) {
                                const data = item.get('model')
                                data.collapsed = collapsed
                                return true
                            }
                        },
                        'drag-canvas',
                        'zoom-canvas'
                    ]
                },
                // 默认状态下节点的配置
                defaultNode: {
                    type: 'icon-node',
                    size: [120, 40],
                    style: defaultNodeStyle,
                    labelCfg: defaultLabelCfg
                },
                // 默认状态下边的配置，
                defaultEdge: {
                    type: 'flow-line',
                    style: defaultEdgeStyle
                },
                // 各个状态下节点的样式-，例如 hover、selected，3.1 版本新增。
                nodeStateStyles: defaultStateStyles,

                // 各个状态下边的样式-，例如 hover、selected，3.1 版本新增。
                edgeStateStyles: defaultStateStyles,
                // 布局配置项
                layout: defaultLayout
            })
            this.graph.data(treedata)

            // 根据提供的数据渲染视图。
            this.graph.render()
            // 让画布内容适应视口。
            this.graph.fitView()
            // 改变视口的缩放比例，在当前画布比例下缩放，是相对比例。
            this.graph.zoom(1)

            this.graph.on('node:mouseenter', (evt) => {
                const { item } = evt;
                this.graph.setItemState(item, 'hover', true);
            });

            this.graph.on('node:mouseleave', (evt) => {
                const { item } = evt;
                this.graph.setItemState(item, 'hover', false);
            });

            this.graph.on('node:click', (evt) => {
                this.evt = evt
                console.log(this.evt);

                this.targetName = this.evt.target.get('name');
                console.log(this.targetName);


                this.targetModel = this.evt.item.getModel();

                console.log(this.targetModel, ' this.targetModel');

                console.log(treedata, 'treedata');




                if (this.targetName === 'remove-item') {
                    console.log(this.targetModel);
                    this.graph.removeChild(this.targetModel.id);
                    return
                }
                this.dialogVisible = true

            });
        }
    },
    mounted() {
        this.G6init()
    }
}
</script>
<style scoped>
#container {
    height: 100%;
    width: 100%;
}
</style>
  